package com.baosu.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.baosu.Exception.BusinessException;
import com.baosu.domain.Article;
import com.baosu.domain.Category;
import com.baosu.domain.Result;
import com.baosu.domain.Tag;
import com.baosu.service.CategoryService;
import com.baosu.mapper.CategoryMapper;
import com.baosu.util.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class CategoryServiceImpl extends ServiceImpl<CategoryMapper, Category> implements CategoryService{

    @Autowired
    private CategoryMapper categoryMapper;

    @Override
    public Result<Page> pageTagList(int page, int pageSize, String name) {
        Page pageInfo = new Page(page, pageSize);

        LambdaQueryWrapper<Category> queryWrapper = new LambdaQueryWrapper<>();
        if(name != null){
            queryWrapper.like(Category::getName,name);
        }
        //执行查询
        this.page(pageInfo, queryWrapper);
        return Result.ok(pageInfo);
    }

    @Override
    public Result deleteCategory(List<Long> ids) {
        int count = categoryMapper.selectCategoryAndArtcile(ids);
        if(count > 0){
            throw new BusinessException(false, "分类下有文章，不可删除");
        }
        categoryMapper.deleteBatchIds(ids);
        return Result.ok(null).message("删除分类成功");
    }

    @Override
    public Result getArticlelistByCategoryId(int pagenum, int pagesize, Long id) {
        Page<Article> page = new Page<>(pagenum,pagesize);
        List<Article> articleList = categoryMapper.getArticlelistByCategoryId(page, id);
        for (Article article : articleList) {
            String content = article.getContent();
            String prefix = StringUtil.setArticlePrefix(content);
            article.setPrefix(prefix);
        }
        page.setRecords(articleList);
        return Result.ok(page);
    }
}




